package com.csdig.cms.directive;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.csdig.cms.common.ConstantDefine;
import com.csdig.cms.exception.ParamsRequiredException;
import com.csdig.cms.model.Channel;
import com.csdig.cms.utils.CacheUtils;
import com.csdig.cms.utils.DirectiveUtils;
import com.csdig.cms.utils.DirectiveUtils.InvokeType;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Service("navBrandDirective")
public class NavDirective implements TemplateDirectiveModel {

	public static final String CHANNEL_ID = "channel_id";
	
	public static final String FILE_NAME = "file_name";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Integer channelId = DirectiveUtils.getInt(CHANNEL_ID, params);
		List<Channel> list = CacheUtils.getChannelNavList(channelId);
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(DirectiveUtils.OUT_LIST, ObjectWrapper.DEFAULT_WRAPPER.wrap(list));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		InvokeType type = DirectiveUtils.getInvokeType(params);
		// 直接输出
		if (InvokeType.body == type) {
			body.render(env.getOut());
		} else if (InvokeType.sysDefined == type) {
			String fileName = DirectiveUtils.getString(FILE_NAME, params);
			if (StringUtils.isBlank(fileName)) {
				throw new ParamsRequiredException(FILE_NAME);
			}
			env.include(ConstantDefine.FrontPage.TPL_BASE+"/sys_def/"+fileName+".ftl","utf-8",true);
		}
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

}
